package com.dnxh.util;

import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dnxh.config.JwtToken;
import com.dnxh.constant.CommonConstant;
import com.dnxh.entity.BasicInfo;
import com.dnxh.service.AccountService;
import com.dnxh.service.BasicInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

/**
 * The type Log util.
 *
 * @Author 枳湫
 * @Time 2022 /4/12 09:36
 * @Describe Basic_jar
 */
@Slf4j
@Component
public class LogUtil {
	
	@Resource
	private              BasicInfoService  basicInfoService;
	private static final int               LOG_LIST_SIZE = 1000;
	private              ArrayList<String> logList       = new ArrayList<> (LOG_LIST_SIZE);
	
	/**
	 * 操作日志记录
	 *
	 * @param request   the request
	 * @param id        the 被操作人员ID
	 * @param operation the 操作
	 */
	@Async ("operation-log->")
	public void recordOperation (HttpServletRequest request, Long id, int operation) {
		String token = request.getHeader (CommonConstant.TOKEN);
		if (CharSequenceUtil.isEmpty (token)) {
			log.error ("数据错误!无请求头!");
			return;
		}
		String operationName = JwtUtil.decode (token).get (CommonConstant.JWT_USER_NAME).toString ();
		String name = basicInfoService.getOne (Wrappers.<BasicInfo>lambdaQuery ()
				.select (BasicInfo::getNickName)
				.eq (BasicInfo::getId, id)).getNickName ();
		String operationStr = operation == 0 ? "确认" : "取消";
		String text = operationName + "操作" + name + operationStr;
		if (logList.size () == LOG_LIST_SIZE) {
			logList.remove (LOG_LIST_SIZE - 1);
		}
		logList.add (text);
	}
}
